package hong.jun.util;

import org.apache.http.HttpEntity;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.io.*;
import java.util.*;

/**
 * 说明:
 * Created on 2020-7-18 , 0018 16:55
 *
 * @author tiancheng <276013558@qq.com>
 */
public class HttpUtil {

    /**
     * 浏览器图标
     */
    public static final String FAVICON = "/favicon.ico";


    /**
     * Post请求
     *
     * @param uri
     * @param jsonVal
     * @return
     * @throws Exception
     */
    public static String postJSON(String uri, String jsonVal, HashMap<String, String> header) throws Exception {
        CloseableHttpResponse response = null;
        // 获取默认的请求客户端
        CloseableHttpClient client = HttpClients.createDefault();
        String result = null;

        try {
            // 通过HttpPost来发送post请求
            HttpPost httpPost = new HttpPost(uri);
            // 设置请求的header
            httpPost.addHeader("Content-Type", "application/json");
            if (header != null && !header.isEmpty()) {
                header.forEach(httpPost::addHeader);
            }
            // 设置请求配置，包括超时
            RequestConfig requestConfig = RequestConfig.custom()
                    .setConnectTimeout(30000)           // 连接超时，单位毫秒
                    .setSocketTimeout(30000)            // 数据传输超时，单位毫秒
                    .setConnectionRequestTimeout(30000) // 获取连接超时，单位毫秒
                    .build();
            httpPost.setConfig(requestConfig);
            httpPost.setEntity(new StringEntity(jsonVal));
            response = client.execute(httpPost);
            HttpEntity entity = response.getEntity();
            result = EntityUtils.toString(entity, "UTF-8");
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            // 释放资源
            if (client != null) {
                client.close();
            }
            if (response != null) {
                response.close();
            }
        }
        return result;
    }

}
